package com.agent.service.mail.impl;


import com.agent.util.MyPropertiesConfigurer;
import microsoft.exchange.webservices.data.core.ExchangeService;
import microsoft.exchange.webservices.data.core.enumeration.misc.ExchangeVersion;
import microsoft.exchange.webservices.data.core.enumeration.property.BodyType;
import microsoft.exchange.webservices.data.core.enumeration.property.WellKnownFolderName;
import microsoft.exchange.webservices.data.core.enumeration.search.LogicalOperator;
import microsoft.exchange.webservices.data.core.service.folder.Folder;
import microsoft.exchange.webservices.data.core.service.item.EmailMessage;
import microsoft.exchange.webservices.data.core.service.item.Item;
import microsoft.exchange.webservices.data.core.service.schema.EmailMessageSchema;
import microsoft.exchange.webservices.data.credential.ExchangeCredentials;
import microsoft.exchange.webservices.data.credential.WebCredentials;
import microsoft.exchange.webservices.data.property.complex.MessageBody;
import microsoft.exchange.webservices.data.search.FindItemsResults;
import microsoft.exchange.webservices.data.search.ItemView;
import microsoft.exchange.webservices.data.search.filter.SearchFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author superman
 * */
public class ExchangeMail {
    private static final Logger logger = LoggerFactory.getLogger(ExchangeMail.class);

    private static String username = MyPropertiesConfigurer.ctxPropertiesMap.get("mail.username");
    private static String password = MyPropertiesConfigurer.ctxPropertiesMap.get("mail.password");
    private static String demand = MyPropertiesConfigurer.ctxPropertiesMap.get("mail.imapServer");
    private static ExchangeService service;

    /**
     * 初始化连接
     * */
    static {
        service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
        ExchangeCredentials credentials = new WebCredentials(username,password);
        service.setCredentials(credentials);
        try {
            service.setUrl(new URI("https://" + demand + "/ews/exchange.asmx"));
        } catch (URISyntaxException e) {
            logger.error("init exchange mail error |",e);
        }
    }

    /**
     * 使用Exchange协议发送
     * @param subject 邮件主题
     * @param to  收件人
     * @param cc  抄送
     * @param realPath  附件
     *
     * @throws Exception
     */
    public static void doSend(String subject, List<String> to, List<String> cc,
                              String bodyText, String realPath) throws Exception {

        EmailMessage msg = new EmailMessage(service);
        msg.setSubject(subject);
        MessageBody body = MessageBody.getMessageBodyFromText(bodyText);
        body.setBodyType(BodyType.HTML);
        msg.setBody(body);
        for (String s : to) {
            msg.getToRecipients().add(s);
        }
        // for (String s : cc) {
        // msg.getCcRecipients().add(s);
        // }
        if (realPath != null && !"".equals(realPath)) {
            msg.getAttachments().addFileAttachment(realPath);
        }
        msg.send();
    }

    public static void send(String subject, List<String> to, List<String> cc,
                            String bodyText) throws Exception {
        doSend(subject, to, cc, bodyText, null);
    }

    /**
     * 使用Exchange协议接收邮件
     *
     * @throws Exception
     */

    public static ArrayList<Item> GetUnreadEmails() throws Exception {
        ItemView view = new ItemView(Integer.MAX_VALUE);
        FindItemsResults<Item> unRead = Folder.bind(service, WellKnownFolderName.Inbox).findItems(SetFilter(), view);
         /*for (Item item : unRead.getItems()) {
            if (item.getSubject() != null) {
                item.load();
                Document document = Jsoup.parse(item.getBody().toString());
                String plainText = document.select("p").text();
                System.out.println("email is "+ ((EmailMessage) item).getFrom().getName());
                System.out.println("subject is :"+item.getSubject()+"body is :"+plainText);
            }
            // list.Add(item.DateTimeSent.ToString());
        }*/
        return unRead.getItems();

//         int unRead=Folder.bind(service, WellKnownFolderName.Inbox).getUnreadCount();  //未读邮件数量
        // System.out.println(unRead);
    }

    /**
     * 设置获取什么类型的邮件
     *
     * @throws Exception
     */

    private static SearchFilter SetFilter() {
        List<SearchFilter> searchFilterCollection = new ArrayList<SearchFilter>();
        searchFilterCollection.add(new SearchFilter.IsEqualTo(
                EmailMessageSchema.IsRead, false));
        SearchFilter s = new SearchFilter.SearchFilterCollection(
                LogicalOperator.And,searchFilterCollection);

        // 如果要获取所有邮件的话代码改成这样：
//		 searchFilterCollection.add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false));
//		 searchFilterCollection.add(new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, true));
//		 SearchFilter s = new SearchFilter.SearchFilterCollection(LogicalOperator.Or,searchFilterCollection);

        return s;
    }

    public static void main(String[] args) throws Exception {
        List<String> to = new ArrayList<String>();
        to.add("**@**.com");
//        send("test",to,null,"hello");
//        GetUnreadEmails();


    }
}
